<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="6" :xs="24" style="border-right: 1px solid #ececec">
        <div class="head-container">
          <el-row>
            <el-col :span="20">
              <h2>证书绑定</h2>
            </el-col>
          </el-row>
          <div class="iptSea">
            <el-input
              v-model="filterText"
              placeholder="请输入类型"
              clearable
              size="mini"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
        </div>
        <div class="head-container" style="height: 700px; overflow-y: auto">
          <el-tree
            :data="certTypeTreePostData"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="18" :xs="24" style="margin-top: 20px">
        <div class="mb8">
          <el-col :span="20">
            <el-form
              :model="queryParams"
              ref="queryForm"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
            >
              <el-input
                v-model="queryParams.searchValue"
                placeholder="请输入证书/持有人"
                clearable
                size="small"
                style="width: 300px"
              >
                <el-button
                  slot="append"
                  @click="handleQuery"
                  style="
                    height: 40px;
                    background: #1267fa;
                    color: #fff;
                    font-size: 14px;
                  "
                  >搜索</el-button
                >
              </el-input>
            </el-form>
          </el-col>
          <el-col :span="2">
            <el-button
              size="default"
              @click="handleAdd"
              v-hasPermi="['qualification:qualificationCert:add']"
              style="
                margin-right: 10px;
                background-color: #1267fa;
                color: #fff;
                border: none;
              "
            >
              <span>+</span> 新建
            </el-button>
          </el-col>
        </div>

        <el-table
          v-loading="loading"
          :data="qualificationCertList"
          :height="tableHight"
          @selection-change="handleSelectionChange"
        >
          <template slot="empty" class="emptyBg">
            <img src="@/assets/images/empty.jpg" alt="" />
          </template>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="岗位"
            align="center"
            prop="qualificationPostId"
          >
            <template slot-scope="scope">
              {{ scope.row.qualificationPost.name }}
            </template>
          </el-table-column>
          <el-table-column
            label="个人证书"
            align="center"
            prop="qualificationPostId"
          >
            <template slot-scope="scope">
              {{ scope.row.certType.certName }}
            </template>
          </el-table-column>
          <el-table-column
            label="持有人"
            align="center"
            prop="qualificationPostId"
          >
            <template slot-scope="scope">
              {{ scope.row.certInfo.belongerName }}
            </template>
          </el-table-column>
          <el-table-column
            label="到期时间"
            align="center"
            prop="qualificationPostId"
          >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.certInfo.certValidity, "{y}-{m}-{d}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['qualification:qualificationCert:edit']"
                >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['qualification:qualificationCert:remove']"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination
          prev-text="上一页"
          next-text="下一页"
          background
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          layout=" ->,total,sizes, prev, pager, next, jumper "
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 添加或修改岗位-证书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="53%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位" prop="qualificationPostId">
              <treeselect
                :disable-branch-nodes="true"
                v-model="form.qualificationPostId"
                :options="certTypeTreePostData"
                :show-count="true"
                placeholder="请选择岗位"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="个人证书" prop="type">
              <treeselect
                :disable-branch-nodes="true"
                v-model="certTypeId"
                :options="certTypeTreeData"
                :show-count="true"
                placeholder="请选择资质类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="持有人" prop="certInfoId">
              <el-select
                v-model="form.certInfoId"
                :disabled="!(certInfoData && certInfoData.length > 0)"
              >
                <el-option
                  v-for="(item, index) in certInfoData"
                  :key="index"
                  :label="item.belongerName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeselect as treeCertTypeSelect } from "@/api/cert/certType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  listQualificationCert,
  getQualificationCert,
  delQualificationCert,
  addQualificationCert,
  updateQualificationCert,
  exportQualificationCert,
  treeselect,
} from "@/api/qualification/qualificationCert";
import { allListCertInfo } from "@/api/cert/certInfo";

export default {
  name: "QualificationCert",
  components: { Treeselect },
  data() {
    return {
      tableHight: window.innerHeight - 330,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      qualificationCertList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        certTypeId: null,
        certCount: null,
      },
      // 表单参数
      form: {
        certTypeId: [],
      },
      certTypeId: null,
      belonger: "",
      // 表单校验
      rules: {
        qualificationPostId: [
          { required: true, message: "请选择岗位", trigger: "blur" },
        ],
        certInfoId: [
          {
            required: true,
            message: "请先选择证书再选择持有人",
            trigger: "blur",
          },
        ],
      },
      filterText: "",
      certInfoData: [],
      certTypeTreePostData: [],
      certTypeTreeData: [],
      treeProps: {
        children: "children",
        label: "label",
      },
    };
  },
  watch: {
    certTypeId(value) {
      if (value) {
        this.allListCertInfo({
          certTypeId: value,
        });
      } else {
        this.certInfoData = [];
      }
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.tableHight = window.innerHeight - 330;
      })();
    };
  },
  activated() {
    this.tableHight = window.innerHeight - 330;
  },
  methods: {
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // selectCertType(node) {
    //   this.form.certInfoId = null;
    // this.allListCertInfo({
    //   certTypeId: node.id
    // })
    // },
    allListCertInfo(query) {
      allListCertInfo(query).then((response) => {
        this.certInfoData = response.data;
        if (response.data.length === 0) {
          this.msgError("此证书下没有持有人");
        }
      });
    },
    certTypesFormat(row, column) {
      let certNames = [];
      if (row.certTypes) {
        row.certTypes.forEach((item) => {
          certNames.push(item.certName);
        });
      }
      return certNames.join(",");
    },
    getTreeselect() {
      //0 类型 1证书 3 岗位
      treeselect().then((response) => {
        this.certTypeTreePostData = response.data;
        this.createAllowedTree(this.certTypeTreePostData, ["0", "1"]);
      });
      treeCertTypeSelect().then((response) => {
        this.certTypeTreeData = response.data;
        this.createAllowedTree(this.certTypeTreeData, ["0"]);
      });
    },
    createAllowedTree(treeData, disableArray) {
      treeData.forEach((item) => {
        console.log(item.type);
        if (item.children && item.children.length > 0) {
          this.createAllowedTree(item.children, disableArray);
        } else {
          if (item.type == "0") {
            item.children = [];
          }
          item.isDisabled = disableArray.includes(item.type) ? true : false;
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.queryParams.qualificationPostId = data.id;
      this.getList();
    },

    /** 查询岗位-证书列表 */
    getList() {
      this.loading = true;
      listQualificationCert(this.queryParams).then((response) => {
        this.qualificationCertList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        qualificationPostId: null,
        certInfoId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.qualificationPostId = "";
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.certTypeId = null;
      this.certInfoData = [];
      this.open = true;
      this.title = "添加岗位-证书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getQualificationCert(id).then((response) => {
        this.form = response.data;
        this.certTypeId = this.form.certInfo.certTypeId;
        this.allListCertInfo({ certTypeId: this.certTypeId });
        this.open = true;
        this.title = "修改岗位-证书";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateQualificationCert(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addQualificationCert(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delQualificationCert(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有岗位-证书数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportQualificationCert(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
  },
};
</script>
<style lang="less" scoped>
.app-container {
  height: 100%;
}
.vue-treeselect__no-children-tip {
  display: none;
}

.activeNode {
  display: none;
}

.el-tree-node__content:hover .activeNode {
  display: inline-block;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-form {
  .el-input {
    /deep/.el-input__inner {
      height: 40px;
    }
  }
}
.iptSea {
  /deep/.el-input__inner {
    height: 40px;
  }
}
/deep/input::-webkit-input-placeholder {
  font-size: 14px;
}
.mb8 {
  display: flex;
  justify-content: space-between;
}
.el-pagination {
  margin-top: 24px;
  /deep/ .el-pagination__total {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    margin-right: 25px;
  }
  /deep/ .btn-prev {
    width: 80px;
    height: 40px;
    text-align: center;
  }
  /deep/ .btn-next {
    width: 80px;
    height: 40px;
    text-align: center;
  }
  /deep/ .number {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .el-input__inner {
    // width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .more {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
  /deep/ .el-pagination__jump {
    .el-input__inner {
      width: 40px;
      height: 40px;
    }
  }
}
</style>
